﻿using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using LocalizationUtils;
using LocalizationUtils.Utils;
using UnityEngine;

namespace LocalizationUtils
{
    [DisallowMultipleComponent]
    [RequireComponent(typeof(RectTransform))]
    [AddComponentMenu("UI/RegexHyperLinkUGUIText", 11)]
    [ExecuteAlways]
    public class RegexHyperLinkUGUIText : HyperLinkTextBase
    {
        public bool _arabicMultiLine = false;

        public override string text
        {
            get { return base.text; }
            set => this.SetUIText(value);
        }

        protected override void Awake()
        {
            base.Awake();
            this.SetArab(_arabicMultiLine);
        }

        private List<Entry> _entries = new List<Entry>();

        class Entry
        {
            public string RegexPattern;
            public Color Color;
            public Action<string> Callback;

            public Entry(string regexPattern, Color color, Action<string> callback)
            {
                this.RegexPattern = regexPattern;
                this.Color = color;
                this.Callback = callback;
            }
        }

        public void AddLinkInfo(string regexPattern, Action<string> onClick)
        {
            AddLinkInfo(regexPattern, color, onClick);
        }

        public void AddLinkInfo(string regexPattern, Color color, Action<string> onClick)
        {
            if (string.IsNullOrEmpty(regexPattern) || onClick == null)
            {
                return;
            }

            _entries.Add(new Entry(regexPattern, color, onClick));
        }

        public override void RemoveListeners()
        {
            base.RemoveListeners();
            _entries.Clear();
        }

        protected override void AddListeners()
        {
            foreach (var entry in _entries)
            {
                foreach (Match match in Regex.Matches(text, entry.RegexPattern))
                {
                    AddLinkInfo(match.Index, match.Value.Length, entry.Color, entry.Callback);
                }
            }
        }

        private void OnDestroy()
        {
            RemoveListeners();
        }
    }
}